#encoding=utf-8
from __future__ import division

import sys
import os
import datetime
import time
import math
import ujson
import uuid
import urllib
from urlparse import urlparse, parse_qsl
from django.db import transaction
import requests
from django.contrib import auth
from django.template import RequestContext
from django.core.cache import cache
from django_redis import get_redis_connection
from django.core.servers.basehttp import FileWrapper
from django.http import StreamingHttpResponse
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
from django.db.models import Count, Max, F, Q
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

from andy_manager import settings
from websys.models import (
    UserInfo,AgentInfo,WithdrawRecord,AgentBank,UserConsumeRecord,AgentRecharge,Oper_Record
)

import  websys.fun as fun
from websys import (
    webconfig,db_redis
)

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
                    #代理状态
                    url(r'^agentstatus', 'websys.view.sysoper.op_agentstatus', name='op_agentstatus'),
                       #审核代理
                    url(r'^agentcheck', 'websys.view.sysoper.op_agentcheck', name='op_agentcheck'),
                       #玩家状态
                    url(r'^userstatus', 'websys.view.sysoper.op_userstatus', name='op_userstatus'),
                       #玩家充值
                    url(r'^userpoint', 'websys.view.sysoper.op_userpoint', name='op_userpoint'),
                    # 代理充值
                    url(r'^agentpoint', 'websys.view.sysoper.op_agentpoint', name='op_agentpoint'),
                       #代理结算
                       url(r'^agent/settlement', 'websys.view.sysoper.agent_settle', name='agent_settle'),
                       #获取登陆的classid
                       url(r'^agentclassid', 'websys.view.sysoper.agent_classid', name='agent_classid'),
                    #提现状态
                       url(r'^withdrawstatus', 'websys.view.sysoper.op_withdrawstatus', name='op_withdrawstatus'),
                       #代理银行
                       url(r'^getbank', 'websys.view.sysoper.op_getbank', name='op_getbank'),
                       url(r'^getip', 'websys.view.sysoper.op_getip', name='op_getip'),
                       #二维码
                       url(r'^qrcode', 'websys.view.sysoper.op_get_qrcode', name='op_get_qrcode'),
                       url(r'^img_qrcode', 'websys.view.sysoper.op_get_qrcodeimg', name='op_get_qrcodeimg'),
                    #代理提成操作
                    url(r'^agent_money', 'websys.view.sysoper.op_agent_money', name='op_agent_money'),

    )

@csrf_exempt
@login_required(login_url="/xadmin/")
def op_agent_money(request):
    ret = {"ret": 0, "msg": ""}
    _id = request.POST["id"]
    act = request.POST["point"]
    type = request.POST['type']
    username=request.user.username
    if AgentInfo.objects.filter(pk=_id).exists():
        record = AgentInfo.objects.get(pk=_id)
        if int(record.allmoney)<int(act):
            ret["ret"] = -2
            ret["msg"] = "该玩家的提成不足!"
            return HttpResponse(ujson.dumps(ret))
        record.allmoney -=int(act)
        record.save()
        oper_record=Oper_Record()
        oper_record.account=record.account
        oper_record.account_type=2
        oper_record.oper_type=3
        oper_record.number= -int(act)
        oper_record.opers=username
        oper_record.save()
        ret["ret"] = 0
        ret["msg"] = "扣除成功!"
    else:
        ret["ret"] = -1
        ret["msg"] = "充值失败,充值账号传入错误!"
    return HttpResponse(ujson.dumps(ret))




#获取 ip
@csrf_exempt
def op_getip(request):
    ret = {"ip": ""}
    tip=request.META["REMOTE_ADDR"]
    if(tip.find(',')>0):
        tip=tip[0:tip.find(',')]
    ret['ip']=tip
    return HttpResponse(ujson.dumps(ret))

#生成二维码
@csrf_exempt
def op_get_qrcode(request):
    import qrcode
    qr = qrcode.QRCode(
    version=2,#尺寸大小
    error_correction=qrcode.constants.ERROR_CORRECT_L,#容错率
    box_size=10,#二维码像素大小
    border=1)
    t_path="http://"+request.META['HTTP_HOST']+"/xadmin/"
    qr.add_data(t_path)
    qr.make(fit=True)
    img = qr.make_image()
    t_url=settings.UPLOAD_ROOT+"/dhqme_qrcode.png"
    img.save(t_url)
    return HttpResponse("<img src='/"+t_url+"'>")
#生成二维码带图片
@csrf_exempt
def op_get_qrcodeimg(request):
    import qrcode
    from PIL import Image
    qr = qrcode.QRCode(
    version=2,#尺寸大小
    error_correction=qrcode.constants.ERROR_CORRECT_H,#容错率
    box_size=10,#二维码像素大小
    border=1)
    t_path="http://"+request.META['HTTP_HOST']+"/xadmin/"
    qr.add_data(t_path)
    qr.make(fit=True)
    img = qr.make_image()
    img = img.convert("RGBA")#保留原色

    icon = Image.open(settings.UPLOAD_ROOT+"/user.png")

    img_w, img_h = img.size
    factor = 4
    size_w = int(img_w / factor)
    size_h = int(img_h / factor)

    icon_w, icon_h = icon.size
    if icon_w > size_w:
        icon_w = size_w
    if icon_h > size_h:
        icon_h = size_h
    icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)

    w = int((img_w - icon_w) / 2)
    h = int((img_h - icon_h) / 2)
    img.paste(icon, (w, h), icon)

    t_url=settings.UPLOAD_ROOT+"/dhqme_qrcode_img.png"
    img.save(t_url)
    return HttpResponse("<img src='/"+t_url+"'>")

#加权限，不要给非代理的数据操作
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_agentstatus(request):
    ret = {"ret": 0, "msg": ""}
    _id = request.POST["id"]
    act = request.POST["type"]
    #是否存在
    if AgentInfo.objects.filter(pk=_id).exists():
        record = AgentInfo.objects.get(pk=_id)
        record.status=int(act)
        record.save()
        #修改user的isaff
        user = User.objects.get(username=record.account)
        user.is_staff=int(act)
        user.save()
    else:
        ret["ret"] = -1
        ret["msg"] = "error record"

    return HttpResponse(ujson.dumps(ret))

@csrf_exempt
@login_required(login_url="/xadmin/")
def op_agentcheck(request):
    ret = {"ret": 0, "msg": ""}
    _id = request.POST["id"]
    act = request.POST["type"]
    #是否存在
    if AgentInfo.objects.filter(pk=_id).exists():
        record = AgentInfo.objects.get(pk=_id)
        record.ischeck=int(act)
        record.save()
        #修改user的isaff
        user = User.objects.get(username=record.account)
        user.is_staff=int(act)
        user.save()
    else:
        ret["ret"] = -1
        ret["msg"] = "error record"

    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_userstatus(request):
    ret = {"ret": 0, "msg": ""}
    _id = request.POST["id"]
    act = request.POST["type"]
    #是否他的会员
    login_uid=request.user.username
    login_cid='1'
    if AgentInfo.objects.filter(account=login_uid).exists():
        ag_info=AgentInfo.objects.get(account=login_uid)
        login_cid=ag_info.classid
    #是否存在
    if UserInfo.objects.filter(pk=_id,agentid__classid__startswith=login_cid).exists():
        record = UserInfo.objects.get(pk=_id)
        record.status=int(act)
        record.save()

    else:
        ret["ret"] = -1
        ret["msg"] = "error record"

    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_userpoint(request):
    if webconfig.RECHARGE_DELELTE:
        ret = {"ret": 0, "msg": ""}
        _id = request.POST["id"]
        act = request.POST["point"]
        type = request.POST['type']
        #print type,type(type)
        username = request.user.username

        login_user = None
        isagent = AgentInfo.objects.filter(account=username).exists()
        if isagent:
            agents=AgentInfo.objects.get(account=username)
            login_user = agents
        if UserInfo.objects.filter(pk=_id).exists():
            record = UserInfo.objects.get(pk=_id)
            parentid = record.agentid_id
            classid = AgentInfo.objects.get(id=parentid).classid
            point = record.gamepoint
            if parentid != None:
                agent_info = AgentInfo.objects.get(id=parentid)
                gamepoint = agent_info.gamepoint
                try:
                    with transaction.commit_on_success():
                        cur = '+'
                        do_type=99
                        if int(type)==0 and isagent:
                            if gamepoint < int(act):
                                ret["ret"] = -3
                                ret["msg"] = "该账户上级代理游戏币不足"
                                return HttpResponse(ujson.dumps(ret))
                        elif int(type)==1:
                            if point > int(act):
                                cur = '-'
                                do_type=98
                            else:
                                ret["ret"] = -3
                                ret["msg"] = "游戏币不足"
                                return HttpResponse(ujson.dumps(ret))
                        exec ('record.gamepoint' + cur + '=' + str(int(act)))

                        record.save()
                        ret["point"] =record.gamepoint
                        #流水消费表
                        ucr=UserConsumeRecord()
                        ucr.gameid=0
                        ucr.typeid=do_type
                        ucr.lastpoint=record.gamepoint
                        ucr.uid_id=_id
                        ucr.remark=username
                        ucr.requestkey=request.user.username
                        exec ('ucr.consumepoint'+'='+cur+str(int(act)))
                        ucr.save()
                        if int(type)==0 and isagent:
                            agent_info.gamepoint -= int(act)
                            agent_info.save()
                            ret["point"] = record.gamepoint
                            # ucr = AgentRecharge()
                            # ucr.operid = login_user
                            # ucr.agentid = agent_info.id
                            # ucr.username = agent_info.username
                            # ucr.lastpoint = agent_info.gamepoint
                            # ucr.amount = -(int(act))
                            # ucr.save()
                        elif int(type)==1 and isagent:
                            #print '--------this s s s s '
                            agent_info.gamepoint += int(act)
                            agent_info.save()
                            ret["point"] = record.gamepoint
                            # ucr = AgentRecharge()
                            # ucr.operid = login_user
                            # ucr.agentid = agent_info.id
                            # ucr.username = agent_info.username
                            # ucr.lastpoint = agent_info.gamepoint
                            # ucr.amount =(int(act))
                            # ucr.save()
                        if int(type)==0:
                            #print '0000000000000000000'
                            oper_record = Oper_Record()
                            oper_record.account = record.uid
                            oper_record.account_type = 1
                            oper_record.oper_type = 1
                            oper_record.number = int(act)
                            oper_record.opers = username
                            oper_record.save()
                        else:
                            oper_record = Oper_Record()
                            oper_record.account = record.uid
                            oper_record.account_type = 1
                            oper_record.oper_type = 2
                            oper_record.number = -int(act)
                            oper_record.opers = username
                            oper_record.save()
                except:
                    ret["ret"] = -5
                    ret["msg"] = "充值失败！"
            else:
                ret["ret"] = -4
                ret["msg"] = "该用户无上级代理"
        else:
            ret["ret"] = -1
            ret["msg"] = "充值失败,充值账号传入错误!"
        return HttpResponse(ujson.dumps(ret))
    else:
        ret = {"ret": 0, "msg": ""}
        _id = request.POST["id"]
        act = request.POST["point"]

        if not request.user.is_superuser:
            ret["ret"] = -2
            ret["msg"] = "error role"
        #是否存在
        elif UserInfo.objects.filter(pk=_id).exists():
            record = UserInfo.objects.get(pk=_id)
            record.gamepoint+=int(act)
            record.save()
            ret["point"] =record.gamepoint;
            #流水消费表
            ucr=UserConsumeRecord()
            ucr.gameid=0
            ucr.typeid=99
            ucr.consumepoint=act
            ucr.lastpoint=record.gamepoint
            ucr.uid_id=_id
            ucr.remark='admin'
            ucr.requestkey=request.user.username
            ucr.save()
        else:
            ret["ret"] = -1
            ret["msg"] = "error record"

        return HttpResponse(ujson.dumps(ret))
# @csrf_exempt
# @login_required(login_url="/xadmin/")
# def op_userpoint(request):
#     ret = {"ret": 0, "msg": ""}
#     _id = request.POST["id"]
#     act = request.POST["point"]
#
#     if not request.user.is_superuser:
#         ret["ret"] = -2
#         ret["msg"] = "error role"
#     #是否存在
#     elif UserInfo.objects.filter(pk=_id).exists():
#         record = UserInfo.objects.get(pk=_id)
#         record.gamepoint+=int(act)
#         record.save()
#         ret["point"] =record.gamepoint;
#         #流水消费表
#         ucr=UserConsumeRecord()
#         ucr.gameid=0
#         ucr.typeid=99
#         ucr.consumepoint=act
#         ucr.lastpoint=record.gamepoint
#         ucr.uid_id=_id
#         ucr.remark='admin'
#         ucr.requestkey=request.user.username
#         ucr.save()
#     else:
#         ret["ret"] = -1
#         ret["msg"] = "error record"
#
#     return HttpResponse(ujson.dumps(ret))

@csrf_exempt
@login_required(login_url="/xadmin/")
def op_agentpoint(request):
    ret = {"ret": 0, "msg": ""}
    _id = request.POST["id"]
    act = request.POST["point"]
    type = request.POST['type']
    username=request.user.username

    login_user = None
    op = 'admin'
    isagent = AgentInfo.objects.filter(account=username).exists()
    if isagent:
        agents = AgentInfo.objects.get(account=username)
        login_user = agents
        op = agents.account

    #是否存在
    if AgentInfo.objects.filter(pk=_id).exists():
        record = AgentInfo.objects.get(pk=_id)
        parentid = record.parentid_id
        point = record.gamepoint
        try:
            with transaction.commit_on_success():
                # print '-------------', int(act)
                cur = '+'
                if int(type)==0 and parentid!=None:
                    agent_info = AgentInfo.objects.get(id=parentid)
                    gamepoint = agent_info.gamepoint
                    if gamepoint < int(act):
                        ret["ret"] = -3
                        ret["msg"] = "该账户上级代理游戏币不足"
                        return HttpResponse(ujson.dumps(ret))
                if int(type) == 1:
                    if point > int(act):
                        cur = '-'

                    else:
                        ret["ret"] = -3
                        ret["msg"] = "游戏币不足"
                        return HttpResponse(ujson.dumps(ret))
                exec ('record.gamepoint' + cur + '=' + str(int(act)))
                record.save()
                # 流水消费表
                ucr = AgentRecharge()
                ucr.operid = login_user
                ucr.agentid = _id
                # print '==========',username
                ucr.username = record.username
                ucr.lastpoint = record.gamepoint
                exec ('ucr.amount'+'='+cur+str(int(act)))
                ucr.save()

                if int(type)==0 and parentid!=None:
                    agent_info.gamepoint -= int(act)
                    agent_info.save()
                    ret["point"] = record.gamepoint
                    ucr = AgentRecharge()
                    ucr.operid = login_user
                    ucr.agentid = agent_info.id
                    ucr.username = agent_info.username
                    ucr.lastpoint = agent_info.gamepoint
                    ucr.amount = -(int(act))
                    ucr.save()
                if int(type) == 0:
                    # print '0000000000000000000'
                    oper_record = Oper_Record()
                    oper_record.account = record.account
                    oper_record.account_type = 2
                    oper_record.oper_type = 1
                    oper_record.number = int(act)
                    oper_record.opers = username
                    oper_record.save()
                else:
                    oper_record = Oper_Record()
                    oper_record.account = record.account
                    oper_record.account_type = 2
                    oper_record.oper_type = 4
                    oper_record.number = -int(act)
                    oper_record.opers = username
                    oper_record.save()

        except:
            ret["ret"] = -5
            ret["msg"] = "充值失败！"
    else:
        ret["ret"] = -1
        ret["msg"] = "传入账号错误"

    return HttpResponse(ujson.dumps(ret))

@csrf_exempt
@login_required(login_url="/xadmin/")
def agent_classid(request):
    ret = {"ret": "", "next": [],"add":1}
    us_name = request.user.username

    #是否存在
    if AgentInfo.objects.filter(account=us_name).exists():
        record = AgentInfo.objects.get(account=us_name)
        my_cid=record.classid;
        ret["ret"] =my_cid

        cur_cid=my_cid
        if len(my_cid)/3>=webconfig.AGENT_LEVEL:
            ret['add']=0
        pk_id=request.GET.get("_rel_parentid__id__exact",0)
        if int(pk_id)>0:
            record = AgentInfo.objects.get(pk=pk_id)
            cur_cid=record.classid
            if len(cur_cid)/3>=webconfig.AGENT_LEVEL:
                ret['add']=0
        #可以看的下级帐号
        cur_arr=AgentInfo.objects.filter(classid__startswith=cur_cid).values("account")
        for ii in cur_arr:
            ret['next'].append(ii["account"])
    else:#管理员
        ret["ret"] ="1"
    #print(us_name,'---ajax--agent_classid---',ret)
    return HttpResponse(ujson.dumps(ret))

@csrf_exempt
@login_required(login_url="/xadmin/")
def op_withdrawstatus(request):
    ret = {"ret": 0, "msg": ""}
    _id = request.POST["id"]
    act = int(request.POST["type"])
    #是否存在
    if WithdrawRecord.objects.filter(pk=_id).exists():
        record = WithdrawRecord.objects.get(pk=_id)
        record.status=int(act)
        record.save()
        #修改user的money
        if(act==-1):
                user = AgentInfo.objects.get(account=record.account)
                user.lastmoney+=record.applymoney
                user.save()

    else:
        ret["ret"] = -1
        ret["msg"] = "error record"

    return HttpResponse(ujson.dumps(ret))

@csrf_exempt
@login_required(login_url="/xadmin/")
def op_getbank(request):
    ret = {"ret": 0, "data": {}}
    _id = request.POST["id"]
    #act = request.POST["type"]
    #是否存在
    if AgentBank.objects.filter(pk=_id).exists():
        record = AgentBank.objects.get(pk=_id)
        ret["data"] = {'name':record.truename,'phone':record.phone,'card':record.bankcard,
                       'bank':record.branch+"("+record.get_banktype_display()+")"}
    else:
        ret["ret"] = -1

    return HttpResponse(ujson.dumps(ret))


def agent_settle(request):
    return render(request, 'xadmin/base_site.html', {'string': ''})
    return render(request, 'index.html', {'string': ''})